﻿/*
 * @Author: liuhandong
 * @Date: 2020-12-06 21:57:41
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IMoveQueueAgent
{
    int queueOrder {get;set;}
    void QueueBind(MoveQueue queue);
    void QueueSetIndex(int idx);
    int QueueGetIndex();
    float QueueGetMoveLength();
}

//assume first one is always goes farthest
public class MoveQueue
{
    private List<IMoveQueueAgent> mAgents = new List<IMoveQueueAgent>();
    private List<Vector3> mPath = new List<Vector3>();
    private float mSpace = 1f;

    //return calculated new move index
    public int SetPath(List<Vector3> pt)
    {
        int addPtIdx = 0;
        float rest;
        var currentIdx = GetIndexByLength(mAgents[0].QueueGetMoveLength(), out rest);
        if(Mathf.Approximately(rest, 0))
        {
            //already last one, just extend it
            addPtIdx = currentIdx;
        }
        else 
        {
            //not last one, we should add from next
            addPtIdx = currentIdx + 1;
        }
        for(int i = 0; i < pt.Count; i++)
        {
            int idx = addPtIdx + i;
            if(idx > mPath.Count)
            {
                mPath.Add(pt[i]);
            }
            else
            {
                mPath[idx] = pt[i];
            }
        }
        return addPtIdx;
    }

    public int GetIndexByLength(float length, out float rest)
    {
        rest = length;
        for(int i = 0; i < mPath.Count - 1; i++)
        {
            float len = (mPath[i+1] - mPath[i]).magnitude;
            if(len > length)
            {
                rest = length;
                return i;
            }
            else
            {
                length -= len;
            }
        }
        return mPath.Count - 1;
    }

    public float GetMoveLength(int order)
    {
        if(mAgents.Count == 0)
        {
            return 0;
        }
        else
        {
            return mAgents[0].QueueGetMoveLength() - mSpace * order;
        }
    }

    public Vector3 GetPosByIndex(int index, float rest)
    {
        if(index < 0)
        {
            return mPath[0];
        }
        else if(index >= mPath.Count - 1)
        {
            return mPath[mPath.Count - 1];
        }
        else
        {
            return mPath[index] + (mPath[index + 1] - mPath[index]).normalized * rest;
        }
    }
}
